 #!/usr/bin/env python3
"""
检查数据库中的模型评估记录
"""

import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from backend.config.database import get_db_session
from backend.entities.prediction import ModelEval
from sqlalchemy import desc

def check_model_eval_records():
    """检查数据库中的模型评估记录"""
    print("🔍 检查数据库中的模型评估记录...")
    
    try:
        with get_db_session() as db:
            # 查询所有模型评估记录
            eval_records = db.query(ModelEval).order_by(desc(ModelEval.train_dt)).all()
            
            print(f"📊 总共有 {len(eval_records)} 条模型评估记录")
            
            if not eval_records:
                print("❌ 数据库中没有模型评估记录")
                return
            
            # 按模型分组统计
            model_stats = {}
            for record in eval_records:
                model_name = record.model
                if model_name not in model_stats:
                    model_stats[model_name] = []
                model_stats[model_name].append(record)
            
            print("\n📋 各模型评估记录统计:")
            for model_name, records in model_stats.items():
                latest_record = records[0]  # 最新的记录
                print(f"\n🤖 {model_name.upper()} 模型:")
                print(f"  📅 最新训练日期: {latest_record.train_dt}")
                print(f"  📊 MAE: {latest_record.mae}")
                print(f"  📊 RMSE: {latest_record.rmse}")
                print(f"  📊 R²: {latest_record.r2}")
                print(f"  📊 MAPE: {latest_record.mape}")
                print(f"  📈 总记录数: {len(records)}")
            
            # 检查模型文件是否存在
            print("\n📁 检查模型文件:")
            model_dir = "backend/models/saved_models"
            model_files = {
                'lightgbm': 'lightgbm_model.pkl',
                'xgboost': 'xgboost_model.pkl',
                'mlp': 'mlp_model.pkl',
                'ensemble': 'ensemble_config.json'
            }
            
            for model_name, filename in model_files.items():
                file_path = os.path.join(model_dir, filename)
                file_exists = os.path.exists(file_path)
                print(f"  📄 {model_name}: {filename} - {'✅ 存在' if file_exists else '❌ 不存在'}")
                
                if file_exists:
                    file_size = os.path.getsize(file_path)
                    print(f"      📏 文件大小: {file_size} 字节")
            
            # 分析问题
            print("\n🔍 问题分析:")
            for model_name in ['lightgbm', 'xgboost', 'mlp']:
                has_eval = model_name in model_stats
                has_file = os.path.exists(os.path.join(model_dir, f"{model_name}_model.pkl"))
                
                if has_eval and not has_file:
                    print(f"  ⚠️  {model_name}: 有评估记录但文件不存在")
                elif not has_eval and has_file:
                    print(f"  ⚠️  {model_name}: 有文件但无评估记录")
                elif has_eval and has_file:
                    print(f"  ✅ {model_name}: 评估记录和文件都存在")
                else:
                    print(f"  ❌ {model_name}: 评估记录和文件都不存在")
            
    except Exception as e:
        print(f"❌ 检查失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    check_model_eval_records()